package com.north.light.androidutils.canvas.examprogress.step;

import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;

import com.north.light.androidutils.canvas.examprogress.ExamProgressBarInfo;
import com.north.light.androidutils.log.LogUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * FileName: ExamProgressStepView
 * Author: lzt
 * Date: 2022/7/29 下午 3:44
 * 进度条，阶段图标信息
 */
public class ExamProgressStepView extends LinearLayout {

    private int mMeasureWidth = 0;
    private ExamProgressBarInfo mProgressBarInfo;
    private List<ExamStepView> stepViewList = new ArrayList<>();
    private List<ExamStepInfo> stepInfoList = new ArrayList<>();
    //是否已经初始化过
    private boolean mHadInit = false;

    public ExamProgressStepView(Context context) {
        super(context);
        init();
    }

    public ExamProgressStepView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ExamProgressStepView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public int getViewMeasureWidth() {
        return mMeasureWidth;
    }

    private void init() {
        setGravity(Gravity.CENTER_VERTICAL);
        setOrientation(LinearLayout.HORIZONTAL);
    }


    public void setProgress(ExamProgressBarInfo barInfo) {
        if (barInfo == null) {
            return;
        }
        postDelayed(new Runnable() {
            @Override
            public void run() {
                //更新UI
                mProgressBarInfo = barInfo;
                mMeasureWidth = getMeasuredWidth();
                if (!mHadInit) {
                    updateUI();
                } else {
                    updateUIWithoutInit();
                }
            }
        }, 100);
    }


    private void updateUIWithoutInit() {
        List<Integer> stepInfo = mProgressBarInfo.getStepCount();
        if (stepInfo == null || stepInfo.size() <= 1) {
            clearStepList();
            removeAllViews();
            return;
        }
        int stepTotalCount = stepInfo.size();
        //计算当前进度的分辨率阈值
        float progressPx = mProgressBarInfo.getProgress() / 100.0f;
        //权重累加map
        HashMap<Integer, Integer> stepCountMap = new HashMap<>();
        //计算权重，累加-------------------------------------------------
        for (int i = 0; i < stepTotalCount; i++) {
            int currentStepTotal = stepInfo.get(i);
            stepCountMap.put(i, currentStepTotal);
        }
        updateView(stepTotalCount, stepCountMap, progressPx);
    }

    /**
     * 计算进度，然后分辨率权重设置位置
     */
    private void updateUI() {
        List<Integer> stepInfo = mProgressBarInfo.getStepCount();
        if (stepInfo == null || stepInfo.size() <= 1) {
            clearStepList();
            removeAllViews();
            return;
        }
        removeAllViews();
        clearStepList();
        mHadInit = true;
        int stepTotalCount = stepInfo.size();
        //初始化完成标识
        AtomicInteger initCounter = new AtomicInteger(0);
        //计算当前进度的分辨率阈值
        float progressPx = mProgressBarInfo.getProgress() / 100.0f;
        //权重累加map
        HashMap<Integer, Integer> stepCountMap = new HashMap<>();
        for (int i = 0; i < stepTotalCount; i++) {
            ExamStepView stepView = new ExamStepView(getContext());
            ExamStepInfo stepChildInfo = new ExamStepInfo();
            stepChildInfo.setTitle(String.valueOf(i + 1));
            stepView.setInfo(stepChildInfo);
            addView(stepView);
            stepViewList.add(stepView);
            stepInfoList.add(stepChildInfo);
            //计算权重，累加-------------------------------------------------
            int currentStepTotal = stepInfo.get(i);
            stepCountMap.put(i, currentStepTotal);
            stepView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (initCounter.incrementAndGet() == stepTotalCount) {
                        //全部控件初始化完成
                        updateView(stepTotalCount, stepCountMap, progressPx);
                    }
                }
            }, 50);
        }


    }

    /**
     * 清空阶段信息
     */
    private void clearStepList() {
        stepInfoList.clear();
        stepViewList.clear();
    }


    private void updateView(int stepTotalCount, HashMap<Integer, Integer> stepCountMap, float progressPx) {
        //计算权重，更新UI-----------------------------------------------
        //所有的权重
        float allStepCount = 0;
//        float allCalStepCount = 0;
        HashMap<Integer, Integer> stepCalCountMap = new HashMap<>();
        for (int i = 0; i < stepTotalCount; i++) {
            Integer stepMapCache = stepCountMap.get(i);
            if (stepMapCache != null) {
                allStepCount = allStepCount + stepMapCache;
            }

            if (stepMapCache != null) {
                Integer beforeCount = stepCalCountMap.get(Math.max(0, i - 1));
                if (beforeCount == null) {
                    stepCalCountMap.put(i, stepMapCache);
                } else {
                    int calCount = stepMapCache + beforeCount;
                    stepCalCountMap.put(i, calCount);
                }
//                Integer currentCalCount = stepCalCountMap.get(i);
//                if (currentCalCount != null) {
//                    allCalStepCount = allCalStepCount + currentCalCount;
//                }
            }
        }
        //获取一个权重所占分辨率
        float stepUnitPx = getViewMeasureWidth() / allStepCount;
        //开始设置每一个控件的marginStart
        for (int j = 0; j < stepViewList.size(); j++) {
            ExamStepView cacheUIObj = stepViewList.get(j);
            LinearLayout.LayoutParams cacheParams = (LayoutParams) cacheUIObj.getLayoutParams();
            Integer stepMapInfo = stepCountMap.get(j);
            if (stepMapInfo != null) {
                int objWidth = cacheUIObj.getMeasuredWidth();
                int marginStart = (int) (stepMapInfo * stepUnitPx - objWidth);
                cacheParams.setMarginStart(marginStart);
                cacheUIObj.setLayoutParams(cacheParams);
                //同时，更新进度数据----------------------------
                ExamStepInfo stepCacheInfo = stepInfoList.get(j);

                Integer stepCalUnitCount = stepCalCountMap.get(j);
                if (stepCalUnitCount != null) {
                    //没有超过
                    int currentProgress = (int) ((stepCalUnitCount * 1.0f / allStepCount * 1.0f) * 100.0f);
                    float doingProgress = progressPx * 100.0f;
                    LogUtil.d("距离：currentProgress-- " + currentProgress + " --doingProgress-- " + doingProgress);
                    if (doingProgress >= currentProgress) {
                        stepCacheInfo.setStatus(1);
                    } else {
                        stepCacheInfo.setStatus(0);
                    }
                }
                cacheUIObj.setInfo(stepCacheInfo);
            }
        }
    }
}
